<?php

namespace App\Models;
use App\Notifications\ResetPassword;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Models\Status;
use Illuminate\Support\Facades\Auth;
class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name','email', 'password',
    ];


    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
    /*头像生成
    1 为 gravatar 方法传递的参数 size 指定了默认值 100；
    2 $this->attributes['email'] 获取邮箱地址
    3 使用 trim 方法剔除邮箱的前后空白内容；
    4 strtolower方法 转小写
    5 md5加密哈希值
    6 传给gravatar网址
    ***/
   public function gravatar($size='100')
   {
    $hash=md5(strtolower(trim($this->attributes['email'])));

    return "http://www.gravatar.com/avatar/$hash?s=$size";
   }

   //boot 方法会在用户模型类完成初始化之后进行加载，因此我们对事件的监听需要放在该方法中。
  public static function boot()
  {
        parent::boot(); //调用自身
        //匿名函数调用
        static::creating(function ($user){
          $user->activation_token=str_random(30);
        });

  }
  //调用消息通知
  public function sendPasswordResetNotification($token)
  {
      $this->notify(new ResetPassword($token));

  }

  //一个用户拥有多条微博
  public function statuses()
  {

    return $this->hasMany(Status::class);
  }
  //feed流
  public function feed()
  {        $user_ids = Auth::user()->followings->pluck('id')->toArray();//所有关注的粉丝
           array_push($user_ids,Auth::user()->id);
           return Status::whereIn('user_id',$user_ids)
                          ->with('user')
                          ->orderBy('created_at','desc');
  }

  //单用户获取多粉丝关系列表函数
  public function followers()
  {
     return $this->belongsToMany(User::class,'followers','user_id','follower_id');

  }

  //单用户获取正在关注的粉丝列表
  public function followings()
  {

    return $this->belongsToMany(User::class,'followers','follower_id','user_id');

  }

  //关注动作
  public function follow($user_ids)
  {
       if(!is_array($user_ids)){
         $user_ids=compact("user_ids");
      }

      $this->followings()->sync($user_ids,false);
  }
 //取消关注
 public function unfollow($user_ids)
 {
     if(!is_array($user_ids)){
       $user_ids=compact('user_ids');
     }
    $this->followings()->detach($user_ids);
 }

 //判断当前用户是否关注了某用户
 public function isFollowing($user_ids)
 {
   return  $this->followings->contains($user_ids);
 }


}
